﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;

namespace Web_Oto.Linq
{
    [Serializable]
    public class Repository<T> : IRepository<T> where T : class, Identifiable
    {
        public Repository(DataContext dataContext)
        {
            DataContext = dataContext;
        }

        public DataContext DataContext { get; set; }
        public void Dispose()
        {
            DataContext.Dispose();
        }

        public void Add(T entity)
        {
            DataContext.GetTable<T>().InsertOnSubmit(entity);
        }

        public void Remove(T entity)
        {
            DataContext.GetTable<T>().DeleteOnSubmit(entity);
        }

        public void Remove(IEnumerable<T> collection)
        {
            var records = DataContext.GetTable<T>().ToList();
            foreach (var record in records)
            {
                Remove(record);
            }
        }

        public void RemoveByFilter(Expression<Func<T, bool>> filter)
        {
            var records = GetByFilter(filter);
            foreach (var record in records)
            {
                Remove(record);
            }
        }

        public T GetById(int id)
        {
            return DataContext.GetTable<T>().SingleOrDefault(c => c.Id.Equals(id));
        }

        public IQueryable<T> GetByFilter(Expression<Func<T, bool>> filter)
        {
            return DataContext.GetTable<T>().Where(filter);
        }

        public void Save()
        {
            DataContext.SubmitChanges();
        }

        public IQueryable<T> GetAll()
        {
            return DataContext.GetTable<T>();
        }
    }
}
